var port = null;
//监听来自content.js的信息
chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    //request就是content.js发送过来的消息
    if (request.type == "用户点击了按钮") {
      connectToNativeHost(request.message);
    }
    return true;
  });
 
 
//断开连接时触发
function onDisconnected() {
  console.log(chrome.runtime.lastError);
  port = null;
}
 
//接收到来自exe程序的消息时触发
async function onNativeMessage(message) {
  console.log('接收到从本地应用程序发送来的消息：' + JSON.stringify(message));
  const tabId = await getCurrentTabId()
  chrome.tabs.sendMessage(tabId, JSON.stringify(message), function (response) {});
}
 
//得到当前tabId
function getCurrentTabId() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, function (tabs) {
      resolve(tabs.length ? tabs[0].id : null)
    });
  })
}
 
//连接到本地主机并获得通信端口
function connectToNativeHost(msg) {
  var nativeHostName = "com.film_manage.folder_select"; //本地主机名（就是在注册表中的名字）
  port = chrome.runtime.connectNative(nativeHostName); //根据本地主机名得到通信端口
  port.onMessage.addListener(onNativeMessage); //监听exe程序是否发来消息
  port.onDisconnect.addListener(onDisconnected); //监听是否断开连接
  port.postMessage(msg) //向应用程序发送信息
}